﻿using BBICMS.Model;
using BBICMS.Repository;
using BBICMS.WebUI.Filters;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace BBICMS.WebUI.Areas.Admin.Controllers.api
{
      [SIGAuth]
    public class PhotoAPIController : ApiController
    {
        public ApplicationUnit _unit = new ApplicationUnit();

        [HttpGet]
        [AllowAnonymous]   
        public IEnumerable<ProductPhoto> Get(int Id)
        {
            return this._unit.ProductPhotos.GetAll().Where(p => p.ProductId == Id).ToList();
        }


        [HttpPost]
        [System.Web.Http.Authorize(Roles = "Administrators, Users")]
        public HttpResponseMessage Product(ProductPhoto photo)
        {
            try
            {
                if (ModelState.IsValid)
                {
                  //  photo.Product = _unit.Products.GetById(photo.ProductId);

                    this._unit.ProductPhotos.Add(photo);
                    this._unit.SaveChanges();

                    HttpResponseMessage result =
                        Request.CreateResponse(HttpStatusCode.Created, photo);

                    result.Headers.Location =
                        new Uri(Url.Link("DefaultApi", new { id = photo.Id }));

                    return result;
                }
                else
                {
                    return Request.
                        CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
            }
            catch (Exception ex)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        [HttpDelete]
        [System.Web.Http.Authorize(Roles = "Administrators, Users")]
        public HttpResponseMessage Delete(int id)
        {
            ProductPhoto photo = this._unit.ProductPhotos.GetById(id);

            if (photo == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            this._unit.ProductPhotos.Delete(photo);

            try
            {
                this._unit.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, photo);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
        }

        protected override void Dispose(bool disposing)
        {
            this._unit.Dispose();
            base.Dispose(disposing);
        }
    }
}
